package com.wanmei.realm;
import com.wanmei.pojo.Role;
import com.wanmei.pojo.User;
import com.wanmei.service.PermissionService;
import com.wanmei.service.RoleService;
import com.wanmei.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService usersService;
    @Autowired
    private RoleService rolesService;
    @Autowired
    private PermissionService permissionsService;

    @Override
    public void setName(String name) {
        super.setName("userRealm");
    }

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();
        User user = usersService.getUserByUserName(username);
        Role roles = rolesService.getRoleByRoleId(user.getRid());
        List<String> listPermissions = permissionsService.getPermissionsNameByRoleId(roles.getId());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole(roles.getName());
        info.addStringPermissions(listPermissions);
        return info;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //不實現驗證碼。
        String username = (String) token.getPrincipal();
        User user = usersService.getUserByUserName(username);

        if (user == null) {
            throw new UnknownAccountException();
        }
        if (user.getPassword() == null) {
            return null;
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, user.getPassword(), this.getName());
//        加盐
//            simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(username));
        return info;
    }
}
